package com.flyqiu.form.core.storage;

import com.flyqiu.common.dict.FlyQiuDicData;
import com.flyqiu.form.api.store.FlyQiuFormStoreService;
import com.flyqiu.form.api.store.FlyQiuFormStoreManage;
import com.flyqiu.form.common.exceptions.FlyQiuFormException;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class DefaultFlyQiuFormStoreManage implements FlyQiuFormStoreManage {
    private final ConcurrentHashMap<String, FlyQiuFormStoreService> flyQiuFormStoreMap = new ConcurrentHashMap<>();

    @Override
    public void registerStore(FlyQiuFormStoreService storeService) {
        String storageKey = storeService.getStorageKey();
        if (flyQiuFormStoreMap.containsKey(storageKey)) {
            return;
        }
        flyQiuFormStoreMap.put(storageKey, storeService);
    }

    @Override
    public void unregisterStore(FlyQiuFormStoreService storeService) {
        String storageKey = storeService.getStorageKey();
        if (flyQiuFormStoreMap.containsKey(storageKey)) {
            return;
        }
        flyQiuFormStoreMap.remove(storageKey);
    }

    @Override
    public FlyQiuFormStoreService getStoreService(String dataStorageType, boolean throwException) {
        FlyQiuFormStoreService flyQiuStoreService = flyQiuFormStoreMap.get(dataStorageType);
        if (flyQiuStoreService != null) return flyQiuStoreService;
        if (!throwException) {
            return null;
        }
        throw new FlyQiuFormException("未能找到存储类型为：" + dataStorageType + "的存储服务");
    }

    @Override
    public List<FlyQiuDicData> getStoreDict() {
        return flyQiuFormStoreMap.values().stream().sorted(Comparator.comparingInt(FlyQiuFormStoreService::orderNumber)).map(e -> {
            FlyQiuDicData flyQiuDicData = new FlyQiuDicData();
            flyQiuDicData.setValue(e.getStorageKey());
            flyQiuDicData.setLabel(e.getStorageLabel());
            return flyQiuDicData;
        }).collect(Collectors.toList());
    }
}
